package com.x.crm;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class DocGenerator {
    private static BufferedWriter docfile;

    static {
        try {
            docfile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("doc.txt")),
                    "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws ClassNotFoundException, IOException {
        /*docfile.write("abc");
        docfile.flush();
        docfile.close();*/
        try {
            String packageName = "com.x.crm.controller";
            List<Class<?>> clzs = getClasses(packageName);

            for (Class clz : clzs) {
                if (clz.isAnnotationPresent(Controller.class)) {
                    Method[] methods = clz.getMethods();
                    for (Method method : methods) {
                        if (method.isAnnotationPresent(DocDesc.class)) {

                            docfile.write("\n" + "########################################################################################################################################################################");
                            docfile.write("\n" + "########################################################################################################################################################################");
                            docfile.newLine();
                            printMapping(method, clz);
                            docfile.write("\n" + "########################################################################################################################################################################");
                            docfile.write("\n" + "########################################################################################################################################################################");
                            printParam(method);
                            docfile.write("\n" + "########################################################################################################################################################################");
                            docfile.write("\n" + "########################################################################################################################################################################");
                            docfile.write("\n" + "########################################################################################################################################################################");
                            docfile.write("\n" + "########################################################################################################################################################################");
                        }
                    }
                }
            }
        } finally {
            docfile.flush();
            docfile.close();
        }
    }

    private static void printParam(Method method) throws IOException {
        printInParam(method);
        printOutParam(method);
    }

    private static void printOutParam(Method method) throws IOException {
        Class<?> returnType = method.getReturnType();
        docfile.write("\n" + "<<<<返回参数：");
        int depth = -1;
        Class superClass = returnType.getSuperclass();
        if(superClass == null){
            return;
        }
        while(!superClass.isAssignableFrom(Object.class)){
            printOutField(superClass, depth);
            superClass = superClass.getSuperclass();
        }
        printOutField(returnType, depth);
    }

    private static void printOutField(Class<?> returnType, int depth) {
        depth++;
        if (depth >= 4) {//规定不超过5层递归
            return;
        }
        String prefix = getPrefix(depth, "\t");
        Field[] declaredFields = returnType.getDeclaredFields();
        for (Field outParam : declaredFields) {
            try {
                if (outParam.isAnnotationPresent(DocDesc.class)) {
                    docfile.newLine();
                    docfile.write(prefix+outParam.getName());
                    DocDesc desc = outParam.getAnnotation(DocDesc.class);
                    docfile.write("\t" + desc.value());
//                    docfile.write("\t" + (desc.selective()?"可选":"必填"));

                }
                if (isNotBaseType(outParam)) {
                    printOutField(outParam.getType(), depth);
                }
                if (java.util.List.class.isAssignableFrom(outParam.getType())) {
                    Type fc = outParam.getGenericType();
                    if (fc instanceof ParameterizedType) // 【3】如果是泛型参数的类型
                    {
                        ParameterizedType pt = (ParameterizedType) fc;
                        Class genericClazz = (Class) pt.getActualTypeArguments()[0];
                        printOutField(genericClazz, depth);

                    }
                }
            } catch (Exception e) {

            }
        }
    }

    private static boolean isNotBaseType(Field outParam) {
        if(outParam.getType().isPrimitive()){
            return false;
        }
        if(outParam.getType().getPackage().getName().equals("java.lang")){
            return false;
        }
        if(outParam.getType().getPackage().getName().equals("java.math")){
            return false;
        }
        if(outParam.getType().getName().equals("java.util.Date")){
            return false;
        }
        if(outParam.getType().getPackage().getName().equals("java.sql")){
            return false;
        }
//        return !outParam.getType().isPrimitive() && !outParam.getType().getPackage().getName().equals("java.lang");
        return true;
    }

    private static String getPrefix(int depth, String s) {
        String result = "";
        for (int i = 0; i < depth; i++) {
            result = result + s;
        }
        return result;
    }

    private static void printInParam(Method method) throws IOException {
        Class<?>[] parameterTypes = method.getParameterTypes();
        for (Class para : parameterTypes) {
            if (isNotServletApi(para)) {
                int depth = -1;
                docfile.write("\n" + ">>>>请求参数：");
                printParam(para, depth);
            }
        }
    }

    private static void printParam(Class para, int depth) throws IOException {
        depth++;
        if (depth >= 3) {//规定不超过5层递归
            return;
        }
        Field[] fields = para.getDeclaredFields();

        Class superClass = para.getSuperclass();
        String prefix = getPrefix(depth, "\t");
        while(superClass != null && !superClass.isAssignableFrom(Object.class)){//直到找到object的class
            Field[] superfields = superClass.getDeclaredFields();
            for (Field field : superfields) {
                if (field.isAnnotationPresent(DocDesc.class)) {
                    docfile.newLine();
                    docfile.write(prefix+field.getName());
                    DocDesc desc = field.getAnnotation(DocDesc.class);
                    docfile.write("\t" + desc.value());
                    docfile.write("\t" + (desc.selective()?"可选":"必填"));
                    if (isNotBaseType(field)) {
                        printParam(field.getType(), depth);
                    }
                    if (java.util.List.class.isAssignableFrom(field.getType())) {
                        Type fc = field.getGenericType();
                        if (fc instanceof ParameterizedType) // 【3】如果是泛型参数的类型
                        {
                            ParameterizedType pt = (ParameterizedType) fc;
                            Class genericClazz = (Class) pt.getActualTypeArguments()[0];
                            printParam(genericClazz, depth);

                        }
                    }
                }
            }
            superClass = superClass.getSuperclass();
        }

        for (Field field : fields) {
            if (field.isAnnotationPresent(DocDesc.class)) {
                docfile.newLine();
                docfile.write(prefix+field.getName());
                DocDesc desc = field.getAnnotation(DocDesc.class);
                docfile.write("\t" + desc.value());
                docfile.write("\t" + (desc.selective()?"可选":"必填"));
                if (isNotBaseType(field)) {
                    printParam(field.getType(), depth);
                }
                if (java.util.List.class.isAssignableFrom(field.getType())) {
                    Type fc = field.getGenericType();
                    if (fc instanceof ParameterizedType) // 【3】如果是泛型参数的类型
                    {
                        ParameterizedType pt = (ParameterizedType) fc;
                        Class genericClazz = (Class) pt.getActualTypeArguments()[0];
                        printParam(genericClazz, depth);

                    }
                }
            }
        }
    }

    private static boolean isNotServletApi(Class para) {
        if (para == javax.servlet.http.HttpServletRequest.class) {
            return false;
        }
        if (para == javax.servlet.http.HttpServletRequest.class) {
            return false;
        }
        if (para == javax.servlet.http.HttpSession.class) {
            return false;
        }
        return true;
    }

    private static void printMapping(Method method, Class clz) throws IOException {
        docfile.write("\t\t\t" + method.getAnnotation(DocDesc.class).value() + "\t");
        String[] clzMappings = new String[]{""};
        if (clz.isAnnotationPresent(RequestMapping.class)) {
            Annotation annotation = clz.getAnnotation(RequestMapping.class);
            if (annotation instanceof RequestMapping) {
                clzMappings = ((RequestMapping) annotation).value();
            }
        }
        String[] values = method.getAnnotation(RequestMapping.class).value();
        int i = 0;
        for (String clzMapping : clzMappings) {
            for (String value : values) {
                if (i > 0) {
                    docfile.write("\t或\t");
                }
                docfile.write("[" + clzMapping + value + "]");
                i++;
            }
        }
        docfile.write("\n" + "\t\t\t");
    }

    /**
     * 从包package中获取所有的Class
     *
     * @param packageName
     * @return
     */
    public static List<Class<?>> getClasses(String packageName) {

        //第一个class类的集合
        List<Class<?>> classes = new ArrayList<Class<?>>();
        //是否循环迭代
        boolean recursive = true;
        //获取包的名字 并进行替换
        String packageDirName = packageName.replace('.', '/');
        //定义一个枚举的集合 并进行循环来处理这个目录下的things
        Enumeration<URL> dirs;
        try {
            dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
            //循环迭代下去
            while (dirs.hasMoreElements()) {
                //获取下一个元素
                URL url = dirs.nextElement();
                //得到协议的名称
                String protocol = url.getProtocol();
                //如果是以文件的形式保存在服务器上
                if ("file".equals(protocol)) {
                    //获取包的物理路径
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    //以文件的方式扫描整个包下的文件 并添加到集合中
                    findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
                } else if ("jar".equals(protocol)) {
                    //如果是jar包文件
                    //定义一个JarFile
                    JarFile jar;
                    try {
                        //获取jar
                        jar = ((JarURLConnection) url.openConnection()).getJarFile();
                        //从此jar包 得到一个枚举类
                        Enumeration<JarEntry> entries = jar.entries();
                        //同样的进行循环迭代
                        while (entries.hasMoreElements()) {
                            //获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
                            JarEntry entry = entries.nextElement();
                            String name = entry.getName();
                            //如果是以/开头的
                            if (name.charAt(0) == '/') {
                                //获取后面的字符串
                                name = name.substring(1);
                            }
                            //如果前半部分和定义的包名相同
                            if (name.startsWith(packageDirName)) {
                                int idx = name.lastIndexOf('/');
                                //如果以"/"结尾 是一个包
                                if (idx != -1) {
                                    //获取包名 把"/"替换成"."
                                    packageName = name.substring(0, idx).replace('/', '.');
                                }
                                //如果可以迭代下去 并且是一个包
                                if ((idx != -1) || recursive) {
                                    //如果是一个.class文件 而且不是目录
                                    if (name.endsWith(".class") && !entry.isDirectory()) {
                                        //去掉后面的".class" 获取真正的类名
                                        String className = name.substring(packageName.length() + 1, name.length() - 6);
                                        try {
                                            //添加到classes
                                            classes.add(Class.forName(packageName + '.' + className));
                                        } catch (ClassNotFoundException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return classes;
    }

    public static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, List<Class<?>> classes) {
        //获取此包的目录 建立一个File
        File dir = new File(packagePath);
        //如果不存在或者 也不是目录就直接返回
        if (!dir.exists() || !dir.isDirectory()) {
            return;
        }
        //如果存在 就获取包下的所有文件 包括目录
        File[] dirfiles = dir.listFiles(new FileFilter() {
            //自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
            public boolean accept(File file) {
                return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));
            }
        });
        //循环所有文件
        for (File file : dirfiles) {
            //如果是目录 则继续扫描
            if (file.isDirectory()) {
                findAndAddClassesInPackageByFile(packageName + "." + file.getName(),
                        file.getAbsolutePath(),
                        recursive,
                        classes);
            } else {
                //如果是java类文件 去掉后面的.class 只留下类名
                String className = file.getName().substring(0, file.getName().length() - 6);
                try {
                    //添加到集合中去
                    classes.add(Class.forName(packageName + '.' + className));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
